package com.smart.car.resource.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * 单节点 Redis 配置
 * TODO Component和 Configuration作为配置类注解的差别（能理解为单例和多例）,在于代理。
 *  只有在代理的时候，才会有区别。不然都是同一个单例
 * @author: zoutao
 * @date: 2021-05-06
 */
@Component
public class RedisConfig {

    /**
     * 自定义RedisTemplate配置(序列化机制对象)，主流方式二
     *  目的就是：将JavaBean弄成Json的样式放进redis：修改RedisTemplate的序列化机制，在配置类中配置支持字符串序列化的方法
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        // 设置值序列化方式:值采用json序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

}
